<?php
/**
 * Created by PhpStorm.
 * User: worry
 * Date: 2018/2/7
 * Time: 12:14
 */

namespace backend\services;


use backend\models\ErrorLog;
use backend\models\ErrorLogRecord;
use common\components\Error;
use common\helps\Func;
use common\services\BasicService;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

class ErrorService extends BasicService
{
    public $model_class = '\\backend\\models\\ErrorLog';
    /**
     * 保存错误日志
     * @param array $data
     * @throws \Exception
     */
    public function create($data = [])
    {
        $data['type'] = ArrayHelper::getValue($data, 'type', 'UNKNOWN');
        $data['message'] = ArrayHelper::getValue($data, 'message', 'UNKNOWN');
        //trace 处理
        $trace = ArrayHelper::getValue($data, 'trace');
        if (is_string($trace)) {
            $trace = preg_replace('/(\.js)\?.*?([\:\s\)])/', '$1$2', $trace);
        }

        $data['trace'] = json_encode($trace, JSON_UNESCAPED_UNICODE);
        $data['md5'] = md5($data['type'] . $data['message'] . $data['url'] . json_encode($data['trace']));
        $errorLog = ErrorLog::find()->where(['md5' => $data['md5']])->one() ?: new ErrorLog();
        $errorLog->load(['ErrorLog' => $data]);
        if (!$errorLog->create_time) {
            $errorLog->create_time = date('Y-m-d H:i:s');
        }
        $errorLog->update_time = date('Y-m-d H:i:s');
        $rs = $errorLog->save();
        if (!$rs) {
            Error::exception('保存错误日志失败:' . $this->getError($errorLog));
        }
        $this->createRecord($errorLog);
    }

    /**
     * 保存日志记录
     * @param ErrorLog $data
     * @throws \Exception
     */
    public function createRecord($data)
    {
        $record = new ErrorLogRecord();
        $record->create_time = date('Y-m-d H:i:s');
        $record->error_id = ArrayHelper::getValue($data, 'id', '0');
        $record->ip = ArrayHelper::getValue($_SERVER, 'REMOTE_ADDR', 'UNKNOWN');
        $record->user_agent = ArrayHelper::getValue($_SERVER, 'HTTP_USER_AGENT', 'UNKNOWN');
        $record->system = Func::getClientSystem() ?: 'UNKNOWN';
        $rs = $record->save();
        if (!$rs) {
            Error::exception('保存错误日志记录失败：' . $this->getError($record));
        }
    }

    public function getTableActions($item)
    {
        $action = '<div class="btn-group">';
        $pk = $this->model->primaryKey()[0];
        $action .= "<a href=\"" . Url::toRoute(['show', 'id' => $item[$pk]]) . "\" class=\"btn btn-info\">查看</a>";
        $action .= "<a data-url=\"" . Url::toRoute(['del', 'id' => $item[$pk]]) . "\" class=\"btn btn-danger ajax-click\">删除</a>";
        $action .= '</div>';
        return $action;
    }
}